type RequestParams = {
  url: string;
  method: string;
  data?: any;
  headers?: any;
  loading?: boolean;
  hideError?: boolean;
};

type RequestHeader = {
  Accept:string;
  'Content-Type':string;
  Authorization?:string;
}
// 根据环境不同引入不同api地址
import config from "@/config/index";
import qs from "qs";
import useLoading from "@/hooks/useLoading";
import { useRouter } from "vue-router";
const router = useRouter();

function filterNullProsties(obj = {}) {
  obj = JSON.parse(JSON.stringify(obj));
  for (let key of Object.keys(obj)) {
    if (obj[key] !== 0 && obj[key] !== false && !obj[key]) {
      delete obj[key];
    }
  }
  return obj;
}

// let CT = 'application/x-www-form-urlencoded'
async function service({
  url = "",
  data = {},
  method = "GET",
  headers = {},
  loading = false,
  hideError = false,
}: RequestParams) {
  const { openLoading, closeLoading } = useLoading();
  try {
    // 初始化请求头
    const requestHeaders: RequestHeader = {
      Accept: "application/json, text/plain, */*",
      "Content-Type": "application/json",
      ...headers,
    };
    // 是否显示全屏加载
    if (loading) {
      // loading
      openLoading();
    }

    let st = sessionStorage.getItem("Authorization");
    if (st) {
      requestHeaders["Authorization"] = st; // 请求头带上token
    }
    let response = null;
    data = filterNullProsties(data);
    if (method.toUpperCase() == "GET") {
      let requestUrl = config + url + "?" + qs.stringify(data);
      let res = await fetch(requestUrl, { headers: requestHeaders });
      response = await res.json();
    } else {
      let body: string | FormData = JSON.stringify(data);
      if (requestHeaders["Content-Type"].includes("from")) {
        body = new FormData();
        for (let key in data) {
          body.append(key, data[key]);
        }
      }
      let res = await fetch(config.baseURL + url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        headers: requestHeaders,
        body,
      });
      response = await res.json();
    }

    if (response.status && response.status !== 200) {
      // 登录超时,重新登录
      if (response.status === 401) {
        sessionStorage.removeItem("Authorization");
      }
      if (!hideError) {
        ElMessage.error(
          response.message || response.msg || "您未登录，请登录后再试！"
        );
      }
      router.replace("/");
      return Promise.reject(response || "error");
    }

    return response;
  } catch (error) {
    if (!hideError) {
      ElMessage.error(error.message || error.msg || "请求失败");
    }
    throw error;
  } finally {
    if (loading) {
      closeLoading();
    }
  }
}

export const get = (url = "", data = {}, loading = false) => {
  return service({
    url,
    method: "GET",
    data,
    loading,
  });
};

export const post = (url = "", data = {}, loading = false) => {
  return service({
    url,
    method: "POST",
    data,
    loading,
  });
};

export default service;
